package com.mall.common;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.mall.utils.ThreadLocalUtils;
import jakarta.annotation.Resource;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author: cxx
 * 公共字段自动填充
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Resource
    private ThreadLocalUtils threadLocalUtils;

    @Override
    public void insertFill(MetaObject metaObject) {
        if ("用户注册".equals(threadLocalUtils.get())) {
            threadLocalUtils.remove();
            metaObject.setValue("createDate", LocalDateTime.now());
            metaObject.setValue("updateDate", LocalDateTime.now());
        } else {
            metaObject.setValue("createDate", LocalDateTime.now());
            metaObject.setValue("createUser", Long.valueOf(String.valueOf(StpUtil.getLoginId())));
            metaObject.setValue("updateUser", Long.valueOf(String.valueOf(StpUtil.getLoginId())));
            metaObject.setValue("updateDate", LocalDateTime.now());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        metaObject.setValue("updateUser", Long.valueOf(String.valueOf(StpUtil.getLoginId())));
        metaObject.setValue("updateDate", LocalDateTime.now());

    }
}
